import request from "@/utils/request";
import { getToken } from "@/utils/auth";

// Get the base API URL from environment or use default
const baseURL = import.meta.env.VITE_APP_BASE_API || "";

export default {
  /**
   * Send a message to the AI and get a streaming response
   * @param {string} prompt - The user's message
   * @param {Array} history - Array of previous messages in {role, content} format
   * @param {string} userId - User ID for caching conversation (optional)
   * @param {Function} onMessage - Callback for each message chunk
   * @param {Function} onComplete - Callback when the response is complete
   * @param {Function} onError - Callback for errors
   */
  streamChat(prompt, history, userId, onMessage, onComplete, onError) {
    // Handle case where userId is actually the onMessage callback (backward compatibility)
    if (typeof userId === 'function') {
      onError = onComplete;
      onComplete = onMessage;
      onMessage = userId;
      userId = null;
    }
    
    // Create fetch request for SSE
    const controller = new AbortController();
    const { signal } = controller;
    
    const apiUrl = `${baseURL}/askAi/chat`;
    console.log("Sending AI chat request to:", apiUrl);
    console.log("Request payload:", { prompt, history, userId });
    
    fetch(apiUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'text/event-stream',
        'Authorization': getToken()
      },
      body: JSON.stringify({ prompt, history, userId }),
      signal
    }).then(response => {
      console.log("AI chat response status:", response.status);
      
      if (!response.ok) {
        // 尝试读取详细错误信息
        return response.text().then(errorText => {
          console.error("Error response body:", errorText);
          try {
            const errorJson = JSON.parse(errorText);
            throw new Error(`HTTP error! Status: ${response.status}, Message: ${errorJson.message || errorJson.detail || JSON.stringify(errorJson)}`);
          } catch (e) {
            throw new Error(`HTTP error! Status: ${response.status}, Body: ${errorText}`);
          }
        });
      }
      
      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      
      function read() {
        reader.read().then(({ done, value }) => {
          if (done) {
            console.log("Stream complete");
            if (onComplete) onComplete();
            return;
          }
          
          // Decode the chunk
          const chunk = decoder.decode(value, { stream: true });
          console.log("Received stream chunk:", chunk);
          
          // Parse the chunk as a JSON object
          try {
            if (chunk.trim()) {
              const lines = chunk.split('\n');
              let validDataFound = false;
              
              for (const line of lines) {
                if (line.trim() && line.trim().startsWith('data:')) {
                  const jsonStr = line.trim().substring(5).trim();
                  
                  // 如果数据为空，跳过
                  if (!jsonStr || jsonStr === '') {
                    console.log("Empty data field, skipping");
                    continue;
                  }
                  
                  console.log("Parsed SSE data:", jsonStr);
                  
                  try {
                    const data = JSON.parse(jsonStr);
                    validDataFound = true;
                    
                    // Pass the content to callback
                    if (data.content) {
                      onMessage(data.content);
                    }
                    
                    // If response is complete, call onComplete
                    if (data.isComplete) {
                      console.log("Response complete");
                      if (onComplete) onComplete(data.content);
                      return;
                    }
                  } catch (parseError) {
                    console.error("JSON parse error for:", jsonStr);
                    console.error("Parse error details:", parseError);
                    
                    // 如果是末尾有不完整的JSON，可能是流被截断了
                    if (parseError.message.includes('unexpected end') ||
                        parseError.message.includes('Unexpected end')) {
                      console.log("Possibly incomplete JSON at stream end, continuing");
                    } else {
                      // 对于其他解析错误，尝试提取部分内容（可能是纯文本）
                      if (jsonStr.includes('"content":"')) {
                        const contentMatch = jsonStr.match(/"content":"([^"]*)"/);
                        if (contentMatch && contentMatch[1]) {
                          console.log("Extracted content from malformed JSON:", contentMatch[1]);
                          onMessage(contentMatch[1]);
                        }
                      } else if (!jsonStr.startsWith('{') && !jsonStr.startsWith('[')) {
                        // 如果不是JSON格式，可能是直接的文本内容
                        console.log("Treating as plain text:", jsonStr);
                        onMessage(jsonStr);
                      }
                    }
                  }
                }
              }
              
              // 如果没有找到有效数据但有内容，可能是格式不符合预期
              if (!validDataFound && chunk.trim() && !chunk.includes('data:')) {
                console.log("No valid data format found, trying to parse chunk as plain text");
                // 尝试将整个块作为纯文本处理
                onMessage(chunk.trim());
              }
            }
          } catch (e) {
            console.error('Error parsing SSE data:', e, 'Chunk:', chunk);
            // 继续读取，而不是中止整个流
          }
          
          // Continue reading
          read();
        }).catch(error => {
          console.error("Error reading stream:", error);
          if (onError) onError(error);
        });
      }
      
      read();
    }).catch(error => {
      console.error("AI chat request failed:", error);
      if (onError) onError(error);
    });
    
    // Return function to abort the fetch
    return () => controller.abort();
  },

  /**
   * Send a message to the AI and get a non-streaming response
   * @param {string} prompt - The user's message
   * @param {Array} history - Array of previous messages in {role, content} format
   * @param {string} userId - User ID for caching conversation (optional)
   * @returns {Promise} Promise resolving to the AI response
   */
  async chatWithAi(prompt, history, userId) {
    try {
      console.log("Sending regular AI chat request");
      const response = await request({
        url: "/askAi/completions", // Using the non-streaming endpoint
        method: "post",
        data: {
          prompt,
          history,
          userId
        }
      });
      console.log("Regular AI chat response:", response);
      return response;
    } catch (error) {
      console.error("AI Chat Error:", error);
      throw error;
    }
  },

  /**
   * Clear the conversation history for a user
   * @param {string} userId - User ID whose conversation to clear
   * @returns {Promise} Promise resolving to success message
   */
  async clearConversation(userId) {
    try {
      const response = await request({
        url: `/askAi/conversation/${userId}`,
        method: "delete"
      });
      console.log("Conversation cleared for user:", userId);
      return response;
    } catch (error) {
      console.error("Error clearing conversation:", error);
      throw error;
    }
  }
} 